package controller;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.FormService;
import org.activiti.engine.HistoryService;
import org.activiti.engine.IdentityService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricProcessInstanceQuery;
import org.activiti.engine.impl.RepositoryServiceImpl;
import org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntity;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.runtime.ProcessInstanceQuery;
import org.activiti.engine.task.Task;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import pagemodel.DataGrid;
import pagemodel.HistoryProcess;
import pagemodel.LeaveTask;
import pagemodel.Process;
import pagemodel.RunningProcess;
import po.LeaveApply;
import po.Permission;
import po.Role;
import po.Role_permission;
import po.User;
import po.User_role;
import service.LeaveService;
import service.SystemService;

import com.alibaba.fastjson.JSON;

/**
 * @description 工作流操作控制层
 * @auther 宁晓强
 * @date 2018/12/26 10:43
 */
@Controller
public class ActivitiController {

    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private FormService formService;
    @Autowired
    private IdentityService identityService;
    @Autowired
    private LeaveService leaveService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private HistoryService historyService;
    @Autowired
    private SystemService systemService;

    /**
     * @description 已部署的工作流列表页
     * @auther 宁晓强
     * @date 2018/12/26 15:41
     * @param
     * @return java.lang.String
     */
    @RequestMapping("/process/list")
    public String processList() {
        return "activiti/processList";
    }

    /**
     * @description 工作流列表
     * @auther 宁晓强
     * @date 2018/12/26 15:44
     * @param current
     * @param rowCount
     * @return pagemodel.DataGrid<pagemodel.Process>
     */
    @ResponseBody
    @RequestMapping(value = "/getProcessList")
    public DataGrid<Process> getProcessList(@RequestParam("current") int current, @RequestParam("rowCount") int rowCount) {

        int firstRow = (current - 1) * rowCount;

        // 查询流程定义列表
        List<ProcessDefinition> list = repositoryService.createProcessDefinitionQuery().listPage(firstRow, rowCount);
        // 总数
        int total = repositoryService.createProcessDefinitionQuery().list().size();

        List<Process> processList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            Process process = new Process();
            process.setDeploymentId(list.get(i).getDeploymentId());
            process.setId(list.get(i).getId());
            process.setKey(list.get(i).getKey());
            process.setName(list.get(i).getName());
            process.setResourceName(list.get(i).getResourceName());
            process.setDiagramresourcename(list.get(i).getDiagramResourceName());
            processList.add(process);
        }

        DataGrid<Process> grid = new DataGrid<Process>();
        grid.setCurrent(current);
        grid.setRowCount(rowCount);
        grid.setRows(processList);
        grid.setTotal(total);

        return grid;
    }

    /**
     * @description 删除一个流程定义
     * @auther 宁晓强
     * @date 2018/12/26 15:47
     * @param deployId
     * @return java.lang.String
     */
    @RequestMapping("/delete/deploy")
    public String deleteDeploy(@RequestParam("deployId") String deployId) throws Exception {
        // 删除流程定义
        repositoryService.deleteDeployment(deployId, true);
        return "activiti/processList";
    }

    /**
     * @description 上传文件
     * @auther 宁晓强
     * @date 2018/12/26 15:49
     * @param uploadFile
     * @param request
     * @return java.lang.String
     */
    @RequestMapping("/upload/workflow")
    public String fileupload(@RequestParam MultipartFile uploadFile, HttpServletRequest request) {
        try {
            MultipartFile file = uploadFile;
            String filename = file.getOriginalFilename();
            InputStream is = file.getInputStream();
            // 部署一个流程定义
            repositoryService.createDeployment().addInputStream(filename, is).deploy();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "index";
    }

    /**
     * @description 展示资源
     * @auther 宁晓强
     * @date 2018/12/26 15:52
     * @param pdId
     * @param resource
     * @param response
     * @return void
     */
    @RequestMapping("/showresource")
    public void export(@RequestParam("pdId") String pdId, @RequestParam("resource") String resource, HttpServletResponse response) throws Exception {
        // 查询一个流程定义
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionId(pdId).singleResult();
        // 获取流
        InputStream inputStream = repositoryService.getResourceAsStream(processDefinition.getDeploymentId(), resource);
        ServletOutputStream output = response.getOutputStream();
        IOUtils.copy(inputStream, output);
    }

    /**
     * @description 请假申请页
     * @auther 宁晓强
     * @date 2018/12/26 10:31
     * @param
     * @return java.lang.String
     */
    @RequestMapping("/leave/apply")
    public String leaveApplyPage() {
        return "activiti/leaveApply";
    }

    /**
     * @description 人事审批页
     * @auther 宁晓强
     * @date 2018/12/26 14:37
     * @param
     * @return java.lang.String
     */
    @RequestMapping("/hr/audit")
    public String hrAuditPage() {
        return "activiti/hrAudit";
    }

    /**
     * @description 销假页
     * @auther 宁晓强
     * @date 2018/12/26 14:50
     * @param
     * @return java.lang.String
     */
    @RequestMapping("/report/back")
    public String reportBackPage() {
        return "activiti/reportBack";
    }

    @RequestMapping("/runningprocess")
    public String task() {
        return "activiti/runningprocess";
    }

    @RequestMapping("/index")
    public String my() {
        return "index";
    }

    @RequestMapping("/modifyapply")
    public String modifyapply() {
        return "activiti/modifyapply";
    }

    /**
     * @description 发起请假申请
     * @auther 宁晓强
     * @date 2018/12/26 11:04
     * @param apply
     * @param session
     * @return java.lang.String
     */
    @ResponseBody
    @RequestMapping(value = "/start/leave", method = RequestMethod.POST)
    public String start_leave(LeaveApply apply, HttpSession session) {
        String userId = (String) session.getAttribute("username");
        leaveService.startWorkflow(apply, userId);
        return JSON.toJSONString("success");
    }

    /**
     * @description 部门领导审批页
     * @auther 宁晓强
     * @date 2018/12/26 13:59
     * @param
     * @return java.lang.String
     */
    @RequestMapping("/dept/leader/audit")
    public String deptLeaderAuditPage() {
        return "activiti/deptLeaderAudit";
    }

    /**
     * @description 部门领导审批列表
     * @auther 宁晓强
     * @date 2018/12/26 14:02
     * @param session
     * @param current
     * @param rowCount
     * @return pagemodel.DataGrid<pagemodel.LeaveTask>
     */
    @RequestMapping(value = "/dept/task/list", produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public DataGrid<LeaveTask> getDeptTaskList(HttpSession session,
                                       @RequestParam("current") int current,
                                       @RequestParam("rowCount") int rowCount) {
        DataGrid<LeaveTask> grid = new DataGrid<>();
        grid.setRowCount(rowCount);
        grid.setCurrent(current);
        grid.setTotal(0);
        grid.setRows(new ArrayList<>());

        // 先做权限检查，对于没有部门领导审批权限的用户,直接返回空
        String userId = (String) session.getAttribute("username");
        int uid = systemService.getUidByusername(userId);
        User user = systemService.getUserByid(uid);
        List<User_role> userRoles = user.getUser_roles();
        if (userRoles == null)
            return grid;
        boolean flag = false;//默认没有权限
        for (int k = 0; k < userRoles.size(); k++) {
            User_role ur = userRoles.get(k);
            Role r = ur.getRole();
            int roleId = r.getRid();
            Role role = systemService.getRolebyid(roleId);
            List<Role_permission> p = role.getRole_permission();
            for (int j = 0; j < p.size(); j++) {
                Role_permission rp = p.get(j);
                Permission permission = rp.getPermission();
                if (permission.getPermissionname().equals("部门领导审批"))
                    flag = true;
                else
                    continue;
            }
        }
        // 无权限
        if (flag == false) {
            return grid;
        }
        int firstRow = (current - 1) * rowCount;
        // 查询部门经理审批列表
        List<LeaveApply> results = leaveService.getDeptTaskPage(userId, firstRow, rowCount);
        // 查询总数
        int totalSize = leaveService.getDeptTaskCount(userId);

        List<LeaveTask> tasks = new ArrayList<>();
        for (LeaveApply apply : results) {
            LeaveTask task = new LeaveTask();
            task.setApply_time(apply.getApply_time()); // 申请时间
            task.setUser_id(apply.getUser_id()); // 申请人
            task.setEnd_time(apply.getEnd_time()); // 请假结束时间
            task.setId(apply.getId()); // 任务ID
            task.setLeave_type(apply.getLeave_type()); // 请假类型
            task.setProcess_instance_id(apply.getProcess_instance_id());
            task.setProcessdefid(apply.getTask().getProcessDefinitionId());
            task.setReason(apply.getReason());
            task.setStart_time(apply.getStart_time());
            task.setTaskcreatetime(apply.getTask().getCreateTime());
            task.setTaskid(apply.getTask().getId());
            task.setTaskname(apply.getTask().getName());
            tasks.add(task);
        }
        grid.setRowCount(rowCount);
        grid.setCurrent(current);
        grid.setTotal(totalSize);
        grid.setRows(tasks);
        return grid;
    }

    /**
     * @description 部门经理完成任务
     * @auther 宁晓强
     * @date 2018/12/26 14:29
     * @param session
     * @param req
     * @param taskId
     * @return java.lang.String
     */
    @ResponseBody
    @RequestMapping(value = "/task/dept/complete/{taskId}")
    public String deptComplete(HttpSession session, HttpServletRequest req,
                               @PathVariable("taskId") String taskId) {

        // 先签收
        String userId = (String) session.getAttribute("username");
        taskService.claim(taskId, userId);

        // 审批意见
        String approve = req.getParameter("deptLeaderApprove");

        // 根据任务ID获取任务信息
        // Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
        // 添加一条批注
        // taskService.addComment(taskId, task.getProcessInstanceId(), "本经理的意见呢，就是同意吧");

        // 设置流程变量
        taskService.setVariable(taskId, "初审人备注", "我呢，没什么可说的");

        // 完成
        Map<String, Object> variables = new HashMap<>();
        variables.put("deptleaderapprove", approve);
        taskService.complete(taskId, variables);

        return JSON.toJSONString("success");
    }

    /**
     * @description 人事审批列表
     * @auther 宁晓强
     * @date 2018/12/26 14:39
     * @param session
     * @param current
     * @param rowCount
     * @return pagemodel.DataGrid<pagemodel.LeaveTask>
     */
    @ResponseBody
    @RequestMapping(value = "/hr/task/list", produces = {"application/json;charset=UTF-8"})
    public DataGrid<LeaveTask> getHrTaskList(HttpSession session, @RequestParam("current") int current, @RequestParam("rowCount") int rowCount) {
        DataGrid<LeaveTask> grid = new DataGrid<>();
        grid.setRowCount(rowCount);
        grid.setCurrent(current);
        grid.setTotal(0);
        grid.setRows(new ArrayList<>());
        //先做权限检查，对于没有人事权限的用户,直接返回空
        String userid = (String) session.getAttribute("username");
        int uid = systemService.getUidByusername(userid);
        User user = systemService.getUserByid(uid);
        List<User_role> userroles = user.getUser_roles();
        if (userroles == null)
            return grid;
        boolean flag = false;//默认没有权限
        for (int k = 0; k < userroles.size(); k++) {
            User_role ur = userroles.get(k);
            Role r = ur.getRole();
            int roleid = r.getRid();
            Role role = systemService.getRolebyid(roleid);
            List<Role_permission> p = role.getRole_permission();
            for (int j = 0; j < p.size(); j++) {
                Role_permission rp = p.get(j);
                Permission permission = rp.getPermission();
                if (permission.getPermissionname().equals("人事审批"))
                    flag = true;
                else
                    continue;
            }
        }
        if (flag == false)//无权限
        {
            return grid;
        } else {
            int firstrow = (current - 1) * rowCount;
            List<LeaveApply> results = leaveService.selectHrTaskPage(userid, firstrow, rowCount);
            int totalsize = leaveService.selectHrTaskTotal(userid);
            List<LeaveTask> tasks = new ArrayList<LeaveTask>();
            for (LeaveApply apply : results) {

                // 查看上个人的审批备注，用当前任务ID获取试试
                String taskComment = (String) taskService.getVariable(apply.getTask().getId(), "初审人备注");
                System.out.println("上一步添加的变量：" + taskComment);

                LeaveTask task = new LeaveTask();
                task.setApply_time(apply.getApply_time());
                task.setUser_id(apply.getUser_id());
                task.setEnd_time(apply.getEnd_time());
                task.setId(apply.getId());
                task.setLeave_type(apply.getLeave_type());
                task.setProcess_instance_id(apply.getProcess_instance_id());
                task.setProcessdefid(apply.getTask().getProcessDefinitionId());
                task.setReason(apply.getReason());
                task.setStart_time(apply.getStart_time());
                task.setTaskcreatetime(apply.getTask().getCreateTime());
                task.setTaskid(apply.getTask().getId());
                task.setTaskname(apply.getTask().getName());
                tasks.add(task);
            }
            grid.setRowCount(rowCount);
            grid.setCurrent(current);
            grid.setTotal(totalsize);
            grid.setRows(tasks);
            return grid;
        }
    }

    /**
     * @description 销假任务列表
     * @auther 宁晓强
     * @date 2018/12/26 14:52
     * @param session
     * @param current
     * @param rowCount
     * @return java.lang.String
     */
    @ResponseBody
    @RequestMapping(value = "/report/back/task/list", produces = {"application/json;charset=UTF-8"})
    public String getReportBackTaskList(HttpSession session, @RequestParam("current") int current, @RequestParam("rowCount") int rowCount) {

        int firstRow = (current - 1) * rowCount;
        String userId = (String) session.getAttribute("username");
        List<LeaveApply> results = leaveService.getReportBackTaskList(userId, firstRow, rowCount);
        int totalSize = leaveService.getReportBackTaskCount(userId);

        List<LeaveTask> tasks = new ArrayList<>();
        for (LeaveApply apply : results) {
            LeaveTask task = new LeaveTask();
            task.setApply_time(apply.getApply_time());
            task.setUser_id(apply.getUser_id());
            task.setEnd_time(apply.getEnd_time());
            task.setId(apply.getId());
            task.setLeave_type(apply.getLeave_type());
            task.setProcess_instance_id(apply.getProcess_instance_id());
            task.setProcessdefid(apply.getTask().getProcessDefinitionId());
            task.setReason(apply.getReason());
            task.setStart_time(apply.getStart_time());
            task.setTaskcreatetime(apply.getTask().getCreateTime());
            task.setTaskid(apply.getTask().getId());
            task.setTaskname(apply.getTask().getName());
            tasks.add(task);
        }
        DataGrid<LeaveTask> grid = new DataGrid<LeaveTask>();
        grid.setRowCount(rowCount);
        grid.setCurrent(current);
        grid.setTotal(totalSize);
        grid.setRows(tasks);

        return JSON.toJSONString(grid);
    }


    @RequestMapping(value = "/updatetasklist", produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public String getupdatetasklist(HttpSession session, @RequestParam("current") int current, @RequestParam("rowCount") int rowCount) {
        int firstrow = (current - 1) * rowCount;
        String userid = (String) session.getAttribute("username");
        List<LeaveApply> results = leaveService.getpageupdateapplytask(userid, firstrow, rowCount);
        int totalsize = leaveService.getallupdateapplytask(userid);
        List<LeaveTask> tasks = new ArrayList<LeaveTask>();
        for (LeaveApply apply : results) {
            LeaveTask task = new LeaveTask();
            task.setApply_time(apply.getApply_time());
            task.setUser_id(apply.getUser_id());
            task.setEnd_time(apply.getEnd_time());
            task.setId(apply.getId());
            task.setLeave_type(apply.getLeave_type());
            task.setProcess_instance_id(apply.getProcess_instance_id());
            task.setProcessdefid(apply.getTask().getProcessDefinitionId());
            task.setReason(apply.getReason());
            task.setStart_time(apply.getStart_time());
            task.setTaskcreatetime(apply.getTask().getCreateTime());
            task.setTaskid(apply.getTask().getId());
            task.setTaskname(apply.getTask().getName());
            tasks.add(task);
        }
        DataGrid<LeaveTask> grid = new DataGrid<LeaveTask>();
        grid.setRowCount(rowCount);
        grid.setCurrent(current);
        grid.setTotal(totalsize);
        grid.setRows(tasks);
        return JSON.toJSONString(grid);
    }

    /**
     * @description 任务详情
     * @auther 宁晓强
     * @date 2018/12/26 14:25
     * @param taskId
     * @param response
     * @return java.lang.String
     */
    @ResponseBody
    @RequestMapping(value = "/task/detail")
    public String taskDetail(@RequestParam("taskId") String taskId, HttpServletResponse response) {
        // 查询任务信息
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
        // 查询流程实例信息
        ProcessInstance process = runtimeService.createProcessInstanceQuery().processInstanceId(task.getProcessInstanceId()).singleResult();
        // 查询申请信息
        LeaveApply leave = leaveService.getLeaveApply(new Integer(process.getBusinessKey()));
        return JSON.toJSONString(leave);
    }

    @RequestMapping(value = "/activiti/task-deptleaderaudit")
    String url() {
        return "/activiti/task-deptleaderaudit";
    }

    /**
     * @description 人事完成任务
     * @auther 宁晓强
     * @date 2018/12/26 14:43
     * @param session
     * @param taskId
     * @param req
     * @return java.lang.String
     */
    @ResponseBody
    @RequestMapping(value = "/task/hr/complete/{taskId}")
    public String hrComplete(HttpSession session, HttpServletRequest req,
                             @PathVariable("taskId") String taskId) {
        // 先签收
        String userId = (String) session.getAttribute("username");
        taskService.claim(taskId, userId);

        // 获取审批意见
        String approve = req.getParameter("hrApprove");


        taskService.setVariable("", "", "");

        // 完成
        Map<String, Object> variables = new HashMap<String, Object>();
        variables.put("hrapprove", approve);
        taskService.complete(taskId, variables);

        return JSON.toJSONString("success");
    }

    /**
     * @description 销假完成任务
     * @auther 宁晓强
     * @date 2018/12/26 14:57
     * @param taskId
     * @param req
     * @return java.lang.String
     */
    @ResponseBody
    @RequestMapping(value = "/task/report/complete/{taskId}")
    public String reportBackComplete(@PathVariable("taskId") String taskId, HttpServletRequest req) {
        // 实际休假开始日期
        String realStartTime = req.getParameter("realstart_time");
        // 实际休假结束日期
        String realEndTime = req.getParameter("realend_time");
        leaveService.completeReportBack(taskId, realStartTime, realEndTime);
        return JSON.toJSONString("success");
    }

    @RequestMapping(value = "/task/updatecomplete/{taskid}")
    @ResponseBody
    public String updatecomplete(@PathVariable("taskid") String taskid, @ModelAttribute("leave") LeaveApply leave, @RequestParam("reapply") String reapply) {
        leaveService.updatecomplete(taskid, leave, reapply);
        return JSON.toJSONString("success");
    }


    @RequestMapping("/processinfo")
    @ResponseBody
    public List<HistoricActivityInstance> processinfo(@RequestParam("instanceid") String instanceid) {
        List<HistoricActivityInstance> his = historyService.createHistoricActivityInstanceQuery().processInstanceId(instanceid).orderByHistoricActivityInstanceStartTime().asc().list();
        return his;
    }

    @RequestMapping("/processhis")
    @ResponseBody
    public List<HistoricActivityInstance> processhis(@RequestParam("ywh") String ywh) {
        String instanceid = historyService.createHistoricProcessInstanceQuery().processDefinitionKey("purchase").processInstanceBusinessKey(ywh).singleResult().getId();
        System.out.println(instanceid);
        List<HistoricActivityInstance> his = historyService.createHistoricActivityInstanceQuery().processInstanceId(instanceid).orderByHistoricActivityInstanceStartTime().asc().list();
        return his;
    }

    /**
     * @description 我的请假流程页
     * @auther 宁晓强
     * @date 2018/12/26 15:05
     * @param
     * @return java.lang.String
     */
    @RequestMapping("my/leaves")
    public String myLeavePage() {
        return "activiti/myLeaves";
    }

    /**
     * @description 我发起的请假流程列表
     * @auther 宁晓强
     * @date 2018/12/26 15:07
     * @param session
     * @param current
     * @param rowCount
     * @return pagemodel.DataGrid<pagemodel.RunningProcess>
     */
    @ResponseBody
    @RequestMapping("setup/process/list")
    public DataGrid<RunningProcess> setupProcessList(HttpSession session, @RequestParam("current") int current, @RequestParam("rowCount") int rowCount) {

        int firstRow = (current - 1) * rowCount;
        String userId = (String) session.getAttribute("username");

        // 创建流程查询对象
        ProcessInstanceQuery query = runtimeService.createProcessInstanceQuery();
        int total = (int) query.count();

        // 过滤条件 - leave流程相关、参与人为当前登录用户 - 分页
        List<ProcessInstance> processInstanceList = query.processDefinitionKey("leave").involvedUser(userId).listPage(firstRow, rowCount);
        List<RunningProcess> list = new ArrayList<>();
        for (ProcessInstance processInstance : processInstanceList) {

            // 查询申请信息
            LeaveApply leaveApply = leaveService.getLeaveApply(Integer.parseInt(processInstance.getBusinessKey()));
            // 只获取申请人为当前登录用户的
            if (!leaveApply.getUser_id().equals(userId)) {
                continue;
            }
            RunningProcess process = new RunningProcess();
            process.setActivityid(processInstance.getActivityId()); // 当前节点ID
            process.setBusinesskey(processInstance.getBusinessKey()); // 业务KEY
            process.setExecutionid(processInstance.getId()); // 执行ID
            process.setProcessInstanceid(processInstance.getProcessInstanceId()); // 流程实例ID
            list.add(process);
        }

        DataGrid<RunningProcess> grid = new DataGrid<RunningProcess>();
        grid.setCurrent(current);
        grid.setRowCount(rowCount);
        grid.setTotal(total);
        grid.setRows(list);
        return grid;
    }

    /**
     * @description 我正在参与的请假流程页
     * @auther 宁晓强
     * @date 2018/12/26 15:13
     * @param
     * @return java.lang.String
     */
    @RequestMapping("my/leave/process")
    public String myLeaveProcessPage() {
        return "activiti/myLeaveProcess";
    }

    /**
     * @description 正在参与的正在运行的请假流程
     * @auther 宁晓强
     * @date 2018/12/26 15:22
     * @param session
     * @param current
     * @param rowCount
     * @return pagemodel.DataGrid<pagemodel.RunningProcess>
     */
    @ResponseBody
    @RequestMapping("/involved/process")
    public DataGrid<RunningProcess> involvedProcessList(HttpSession session, @RequestParam("current") int current, @RequestParam("rowCount") int rowCount) {

        int firstRow = (current - 1) * rowCount;
        String userId = (String) session.getAttribute("username");

        ProcessInstanceQuery query = runtimeService.createProcessInstanceQuery();
        int total = (int) query.count();

        List<ProcessInstance> processInstanceList = query.processDefinitionKey("leave").involvedUser(userId).listPage(firstRow, rowCount);
        List<RunningProcess> list = new ArrayList<>();
        for (ProcessInstance processInstance : processInstanceList) {
            RunningProcess process = new RunningProcess();
            process.setActivityid(processInstance.getActivityId());
            process.setBusinesskey(processInstance.getBusinessKey());
            process.setExecutionid(processInstance.getId());
            process.setProcessInstanceid(processInstance.getProcessInstanceId());
            list.add(process);
        }

        DataGrid<RunningProcess> grid = new DataGrid<RunningProcess>();
        grid.setCurrent(current);
        grid.setRowCount(rowCount);
        grid.setTotal(total);
        grid.setRows(list);

        return grid;
    }

    /**
     * @description 我的请假历史
     * @auther 宁晓强
     * @date 2018/12/26 15:27
     * @param
     * @return java.lang.String
     */
    @RequestMapping("/history/process")
    public String historyPage() {
        return "activiti/historyProcess";
    }

    /**
     * @description 我的请假历史列表
     * @auther 宁晓强
     * @date 2018/12/26 15:28
     * @param session
     * @param current
     * @param rowCount
     * @return pagemodel.DataGrid<pagemodel.HistoryProcess>
     */
    @ResponseBody
    @RequestMapping("/history/list")
    public DataGrid<HistoryProcess> getHistoryList(HttpSession session, @RequestParam("current") int current, @RequestParam("rowCount") int rowCount) {

        String userId = (String) session.getAttribute("username");

        // 获取当前用户的历史请假
        HistoricProcessInstanceQuery process = historyService.createHistoricProcessInstanceQuery().processDefinitionKey("leave").startedBy(userId).finished();
        int total = (int) process.count();

        // 分页
        int firstRow = (current - 1) * rowCount;
        List<HistoricProcessInstance> info = process.listPage(firstRow, rowCount);
        List<HistoryProcess> list = new ArrayList<>();
        for (HistoricProcessInstance history : info) {
            HistoryProcess his = new HistoryProcess();
            String businessKey = history.getBusinessKey();
            LeaveApply apply = leaveService.getLeaveApply(Integer.parseInt(businessKey));
            his.setLeaveapply(apply);
            his.setBusinessKey(businessKey);
            his.setProcessDefinitionId(history.getProcessDefinitionId());
            list.add(his);
        }

        DataGrid<HistoryProcess> grid = new DataGrid<HistoryProcess>();
        grid.setCurrent(current);
        grid.setRowCount(rowCount);
        grid.setTotal(total);
        grid.setRows(list);
        return grid;
    }

    /**
     * @description 流程实例图
     * @auther 宁晓强
     * @date 2018/12/26 15:32
     * @param executionId
     * @param response
     * @return void
     */
    @RequestMapping("trace/process/{executionId}")
    public void traceProcess(@PathVariable("executionId") String executionId, HttpServletResponse response) throws Exception {

        // 查询流程实例
        ProcessInstance process = runtimeService.createProcessInstanceQuery().processInstanceId(executionId).singleResult();
        // 获取 Bpmn 模型
        BpmnModel bpmnmodel = repositoryService.getBpmnModel(process.getProcessDefinitionId());
        // 获取所有节点列表
        List<String> activeActivityIds = runtimeService.getActiveActivityIds(executionId);

        // 获取生成器
        DefaultProcessDiagramGenerator generator = new DefaultProcessDiagramGenerator();

        // 获得历史活动记录实体（通过启动时间正序排序，不然有的线可能绘制不出来）
        List<HistoricActivityInstance> historicActivityInstances = historyService.createHistoricActivityInstanceQuery()
                .executionId(executionId)
                .orderByHistoricActivityInstanceStartTime().asc().list();

        // 计算活动线
        List<String> highLightedFlows = leaveService.getHighLightedFlows(
                (ProcessDefinitionEntity) ((RepositoryServiceImpl) repositoryService)
                        .getDeployedProcessDefinition(process.getProcessDefinitionId()),
                historicActivityInstances);

        InputStream inputStream = generator.generateDiagram(bpmnmodel, "png", activeActivityIds, highLightedFlows, "宋体", "宋体", null, 1.0);
        // InputStream in=gen.generateDiagram(bpmnmodel, "png", activeActivityIds);
        ServletOutputStream output = response.getOutputStream();
        IOUtils.copy(inputStream, output);
    }

}
